module.exports = function(app, settings){
	var log4js 		= require('log4js')
		, bcrypt 		= require('bcrypt-as-promised')
		, cookiee   = require("cookie-encryption")
		, csrf 			= require('csurf') // ref: https://github.com/expressjs/csurf
		, debug 		= require('debug')('http')
		, jwt 			= require('jsonwebtoken')
		, randomstring = require("randomstring")
		, url 			= require('url')
		, express 	= require('express')
		, fs				= require('fs')
		, models 		= require("../../models")
		, util 			= require('util');


	var logger 								= log4js.getLogger('http')
		, SALT_WORK_FACTOR 			= 10
		, csrfProtection 				= csrf({ cookie: true })
		, jwtCookie     				= cookiee(settings.adminJwtSecret, settings.adminCookieOptions)
		, router 								= express.Router()
		, Administrator 				= models.Administrator;

	//OAuth token endpoint - return JWT token to client
	router.route('/token')
		.all(function(req, res, next){
			next();
		})
		.post(function(req, res, next){
			//THe POST request put all parameters by x-www-form-urlencoded
			switch(req.body.grant_type){
				case "password":
					//TODO: validate the request is from a trusted client's domain
					var username = req.body.username
						,	password = req.body.password
						,	clientId = req.body.client_id;


					//validate username and password
					Administrator.getAuthenticated(username, password, function(err, user, reason){
			        	if(err) throw err;

			        	if(user !== null){ //success
			        		//Generate JWT token
									var claims = {
									  sub: user.username,
									  iss: req.get('host'),
									  permissions: ['all','upload-photos'] //TODO: get permissions from user table
									};
									var accessToken = jwt.sign(claims, settings.adminJwtSecret
																, {
																		algorithms: ['RS256', 'HS256']
																		, expiresIn: settings.jwt.expiresIn
																}
													);

									debug("Write debug token", settings.adminCookieName);

									//jwtCookie.write(res, accessToken, settings.adminCookieName);
									res.cookie(settings.adminCookieName, accessToken, { signed: true });

									return res.json({
										success: true
										, access_token: accessToken
									});
			        	}else{
			        		return res.json({
				        		success: false,
				        		message: 'AuthFailure'
				        	});
			        	}
			        });
					break;
				default:
					return res.json({
						success: false,
						message: "Not supported grant type"
					});
			}
		});

		app.use('/oauth2', router);
}
